export default {
  namespaced: true,
  state: {
    str: 'lalal',
    cart: uni.getStorageSync('cart') || []
  },
  mutations: {
    //添加一项到购物车
    addToCart(state, goods) {
      let f = state.cart.find(t => t.goods_id === goods.goods_id)
      if (f) {
        f.goods_count++
      } else {
        state.cart.push(goods)
      }
      uni.setStorageSync('cart', state.cart)
    },
    //选中状态
    updateGoodsState(state, goods) {
      let f = state.cart.find(t => t.goods_id === goods.goods_id)
      if (f) {
        f.goods_state = goods.goods_state
      }
      uni.setStorageSync('cart', state.cart)
    },
    //每一项的数量
    updateGoodsCount(state, goods) {
      // console.log(111)
      let f = state.cart.find(t => t.goods_id === goods.goods_id)
      if (f) {
        f.goods_count = goods.goods_count
      }
      uni.setStorageSync('cart', state.cart)
    },
    //删除购物车某一项
    deleteGoodsItem(state, goods) {
      let f = state.cart.find(t => t.goods_id === goods.goods_id)
      // console.log(f)
      // console.log(state.cart)
      if (f) {
        state.cart.forEach((item, i) => {
          item.goods_id == f.goods_id && state.cart.splice(i, 1)
        })
      }
      uni.setStorageSync('cart', state.cart)
    },
    // 更新所有商品的勾选状态
    updateAllGoodsState(state, newState) {
      // console.log('newState', newState)
      // 循环更新购物车中每件商品的勾选状态
      state.cart.forEach(x => x.goods_state = newState)
      // 持久化存储到本地
      uni.setStorageSync('cart', state.cart)
    }
  },
  getters: {
    total(state) {
      let result = 0
      state.cart.forEach(t => result += t.goods_count)
      return result
    },
    // 勾选的商品的总数量
    checkedCount(state) {
      // 先使用 filter 方法，从购物车中过滤器已勾选的商品
      // 再使用 reduce 方法，将已勾选的商品总数量进行累加
      // reduce() 的返回值就是已勾选的商品的总数量
      return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
    },
    // 已勾选的商品的总价
    checkedGoodsAmount(state) {
      // 先使用 filter 方法，从购物车中过滤器已勾选的商品
      // 再使用 reduce 方法，将已勾选的商品数量 * 单价之后，进行累加
      // reduce() 的返回值就是已勾选的商品的总价
      // 最后调用 toFixed(2) 方法，保留两位小数
      return state.cart.filter(x => x.goods_state)
        .reduce((total, item) => total += item.goods_count * item.goods_price, 0)
        .toFixed(2)
    }
  }
}
